package cn.edu.shu.wechat.core.util;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

import javax.xml.transform.stream.StreamSource;

import cn.edu.shu.wechat.core.bean.MessageTypeEnum;
import cn.edu.shu.wechat.core.bean.TextMessage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

import com.google.gson.JsonObject;

import cn.edu.shu.wechat.core.bean.BaseMessage;

public class MessageUtil {
    private static final Logger logger = LoggerFactory.getLogger(MessageUtil.class);

    public Map getMsgType(InputStream in)
    {
        SAXReader reader = new SAXReader();
        Map<String, Object> result = new HashMap<>();
        Document document = null;
        try {
            document = reader.read(in);
        } catch (DocumentException e) {
            logger.error("can not parse xml string :" + in);
        }
        Element root = document.getRootElement();
        for (Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            result.put(element.getName(), element.getStringValue());
        }
        String msgType=(String)result.get("MsgType");
        if(msgType.equals(MessageTypeEnum.TEXTMESSAGE.getMsgType())){
            TextMessage message=new TextMessage();
            message.setCreateTime(Long.parseLong((String) result.get("CreateTime")));
            message.setFromUserName((String)result.get("FromUserName"));
            message.setMsgId(Long.parseLong((String)result.get("MsgId")));
            message.setMsgType((String)result.get("MsgType"));
            message.setToUserName((String)result.get("ToUserName"));
            message.setContent((String)result.get("Content"));
            result.put("message", message);
        }
        return  result;
    }
    /**
     * 根据请求返回的json对象判断是否操作成功
     * @param obj 返回的json对象
     * @return
     */
    public static boolean isSuccess(JsonObject obj){
    	if(obj.get("errcode").getAsInt()==0){
    		return true;
    	}
    	else{
    		logger.error("errcode :"+obj.get("errcode").getAsInt());
    		logger.error("errmsg :"+obj.get("errmsg").getAsString());
    		return false;
    	}
    }
}
